package cn.b504.qpcr.controller;

import cn.b504.qpcr.interfaces.Access;
import cn.b504.qpcr.utils.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileNotFoundException;

@Controller
public class IndexPageController {
  private final Access access;
  private final String idOfCPUHashCode;

  public IndexPageController(Access access, String idOfCPUHashCode) {
    this.access = access;
    this.idOfCPUHashCode = idOfCPUHashCode;
  }

  @RequestMapping(value = "/reg") //  序列化注册
  @ResponseBody
  public boolean reg(@RequestBody String param) {
    boolean result = access.access(param);
    if (result) {
      File dir;
      try {
        dir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
      }
      String data = idOfCPUHashCode + "-" + param;
      String licPath = FileUtils.outputFileWithAbsolutePath(data, dir.getAbsolutePath(), "LIC", "");
      if (licPath.length() == 0) {
        return false;
      }
    }
    return result;
  }

  @RequestMapping(value = "/getKey") //  获取CpuId
  @ResponseBody
  public String getKey() {
    return idOfCPUHashCode;
  }
}
